﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MyTcpIp.tcpAsynService
{
    public class FtpService
    {
        private string ftpServerIP;
        private string ftpRemotePath;
        private string ftpUserID;
        private string ftpPassword;
        private string ftpURI;

        /// <summary>
        /// 连接FTP
        /// </summary>
        /// <param name="FtpServerIP">FTP连接地址</param>
        /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
        /// <param name="FtpUserID">用户名</param>
        /// <param name="FtpPassword">密码</param>
        public FtpService(string ServerIP, string RemotePath, string UserID, string Password)
        {
            ftpServerIP = ServerIP;
            ftpRemotePath = RemotePath;
            ftpUserID = UserID;
            ftpPassword = Password;
            ftpURI = "ftp://" + ftpServerIP + "/"+ ftpRemotePath + "/";
        }

        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="filename">文件名</param>
        public void UploadFile(string FileName)
        {
            FileInfo fileInfo = new FileInfo(FileName);
            string uri = ftpURI + fileInfo.Name;
            FtpWebRequest reqFTP;

            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

            reqFTP.KeepAlive = false;
            reqFTP.UseBinary = true;
            //reqFTP.UsePassive = false;
            reqFTP.Proxy = null;

            reqFTP.ContentLength = fileInfo.Length;
            int BufferSize = 2048;
            byte[] buff = new byte[BufferSize];
            int ContentLength;
            FileStream fs = fileInfo.OpenRead();
            
            try
            {
                Stream strm = reqFTP.GetRequestStream();
                ContentLength = fs.Read(buff, 0, BufferSize);
                while (ContentLength != 0)
                {
                    strm.Write(buff, 0, ContentLength);
                    ContentLength = fs.Read(buff, 0, BufferSize);
                }

                strm.Close();
                fs.Close();
                MessageBox.Show("配置成功，请重启下位机");
            }
            catch (Exception ex)
            {
                MessageBox.Show("下传配置失败"+ex.ToString());
                
                //throw new Exception("Ftphelper Upload Error --> " + ex.Message);
            }
        }
    }
}
